<template>
  <div>
    <el-dialog
    
      :model-value="props.show"
      :title="props.title"
      :width="props.width"
      :draggable="props.draggable"
      :close-on-click-modal="props.modal"
      @close="close"
      @open="open"
      @opened="opened"
      @closed="closed"
      :destroy-on-close="props.destroy"
      :append-to-body="true"
    >
      <slot></slot>
      <template #footer v-if="props.showFooter">
        <div :class="props.btnPosition">
          <div>
            <el-button @click="cancle">取消</el-button>
            <el-button
              type="primary"
              @click="confirm"
              :disabled="props.disabled"
            >
              {{ props.confirmText }}
            </el-button>
          </div>
        </div>
      </template>
      <div style="height: 20px" v-if="!props.showFooter"></div>
    </el-dialog>
  </div>
</template>

<script setup name="MyDialog">
import { nextTick } from 'vue';

const emit = defineEmits([
  'update:show',
  'confirm',
  'close',
  'cancle',
  'open',
  'opened',
  'closed'
]);
const props = defineProps({
  modal: {
    default: false
  },
  show: {
    default: false
  },
  draggable: {
    default: true
  },
  title: {
    default: ''
  },
  width: {
    default: '80%'
  },
  confirmText: {
    default: '确认'
  },
  disabled: {
    default: false
  },
  formRef: {
    default: undefined
  },
  destroy: {
    default: false
  },
  showFooter: {
    default: true
  },
  btnPosition: {
    default: 'bright'
  }
});
const cancle = () => {
  emit('update:show', false);
  emit('cancle');
};
const close = () => {
  emit('update:show', false);
  emit('close');
};
const open = () => {
  let types = ['新增', '添加'];
  let bool = types.some(item => props.title.includes(item));

  if (bool) {
    nextTick(() => {
      if (!props.formRef) return;
      // props.formRef.resetFields();
      setTimeout(() => {
        props.formRef?.clearValidate();
      }, 0);
    });
  }
  if (filterTitle()) {
    setTimeout(() => {
      if (!props.formRef) return;
      props.formRef?.clearValidate();
    }, 0);
  }
  emit('open');
};
const opened = () => {
  emit('opened');
};
const confirm = () => {
  if (props.formRef?.validate) {
    props.formRef.validate(valid => {
      emit('confirm', valid);
    });
  } else {
    emit('confirm');
  }
};
function closed() {
  emit('closed');
}

function filterTitle() {
  let list = ['修改', '编辑'];
  let bool = list.some(item => props.title.includes(item));
  return bool;
}
</script>

<style lang="scss" scoped>
.bright {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.bcenter {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
